package cn.wolfcode.trip.base.controller;

import cn.wolfcode.trip.base.domain.News;
import cn.wolfcode.trip.base.query.NewsQueryObject;
import cn.wolfcode.trip.base.service.INewsService;
import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private INewsService newsService;

    @RequestMapping("/list")
    public String list(Model model,@ModelAttribute("qo") NewsQueryObject qo){
        if (qo.getState() == null){
            qo.setState(News.STATE_NOT_RELEASE);
        }
        //按照创建时间排序
        qo.setOrderBy("createTime desc");
        model.addAttribute("pageInfo",newsService.query(qo));
        return "news/list";
    }

    @RequestMapping("/saveOrUpdate")
    public Object saveOrUpdate(News entity, MultipartFile img){
        if (img != null && img.getContentType().startsWith("image") && img.getSize() > 0){
            String url = UploadUtil.upload(img);
            entity.setCoverUrl(url);
        }
        newsService.saveOrUpdate(entity);
        return "redirect:/news/list.do";
    }

    @RequestMapping(value = "/getContent",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object getContent(Long id){
        return newsService.getContent(id);
    }

    // 更新日报状态（下架或发布,或头条）
    @RequestMapping("/changeState")
    @ResponseBody
    public Object changeState(Long id, Integer state){
        newsService.changeState(id, state);
        return new JSONResult();
    }
}
